package com.project.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.project.bean.ShopBean;
import com.project.bean.UserBean;
import com.project.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;

@Controller
@RequestMapping("user")
public class UserController {
    @Autowired
    private IUserService service;

    @RequestMapping("login")
    public String login(String userName, String pwd, HttpServletRequest request) throws Exception {
//        //调用业务方法得到登陆用户
//        UserBean user = service.login(userName, pwd);
//        if(user == null){
//            return "no";
//        }
//        //在session中，添加登陆信息
//        request.getSession().setAttribute("loginUser", user);
//
//        if("顾客".equals(user.getGrade())){
//            request.getSession().setAttribute("shopMap", new HashMap<Integer, ShopBean>());
//        }
//
//        //将用户信息转化为json字符串
//       String userStr =  new ObjectMapper().writeValueAsString(user);
//       return userStr;

        UserBean user = service.login(userName, pwd);
        System.out.println(user);
        if(user == null){
            return "redirect:/html/login.html?info=loginerror";
        }
        else if ("顾客".equals(user.getGrade())){
            request.getSession().setAttribute("loginUser", user);
            request.getSession().setAttribute("shopMap", new HashMap<Integer, ShopBean>());
            return "redirect:/html/index.html";
        }
        else if ("管理员".equals(user.getGrade())){
            request.getSession().setAttribute("loginUser", user);
            return "redirect:/html/manager/managerIndex.html";
        }
        else{
            request.getSession().setAttribute("loginUser", user);
            return "redirect:/html/send/sendIndex.html";
        }
    }
}
